package com.itcs.app.pay.swiftpass.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itcs.app.pay.model.QrcodePayModel;
import com.itcs.app.pay.model.QrcodePayRes;
import com.itcs.app.pay.model.TradePayModel;
import com.itcs.app.pay.nowpay.constants.PayChannelType;
import com.itcs.app.pay.swiftpass.properties.SwiftpassProperties;
import com.itcs.app.pay.swiftpass.service.SwiftpassService;
import com.itcs.app.pay.swiftpass.util.PaymentKit;
import com.itcs.app.util.HttpUtil;
import com.itcs.app.util.PayChannelCode;
import com.itcs.app.util.XmlJsonUtils;

@Service
public class SwiftpassServiceImpl implements SwiftpassService {
	
	private Log logger = LogFactory.getLog(getClass());

	@Autowired
	private SwiftpassProperties config;
	
	/**
	 * 威富通主扫支付
	 */
	@Override
	public QrcodePayRes pay(QrcodePayModel qrcodePayModel) {
		
		String channelCode = qrcodePayModel.getPayChannelCode();
		String openId = qrcodePayModel.getFilterParams().get("openId");
		String view = "/swiftpass_pay";
		
		Map<String, String> dataMap = new HashMap<String, String>(32);
		dataMap.put("out_trade_no", qrcodePayModel.getTranNO());
		dataMap.put("body", qrcodePayModel.getOrderDetail());
		dataMap.put("total_fee", qrcodePayModel.getTollFare());
		dataMap.put("mch_create_ip", qrcodePayModel.getIp());// 订单生成的机器 IP
		dataMap.put("notify_url", config.getNotifyUrl());
		dataMap.put("nonce_str", "ITC"+System.currentTimeMillis());
		
		dataMap.put("version", config.getVersion());//非必须参数
		dataMap.put("charset", config.getCharset());//非必须参数
		dataMap.put("sign_type", "MD5");//非必须参数
		dataMap.put("time_start", "");//非必须参数
		dataMap.put("attach", "");//非必须参数
		dataMap.put("device_info", "");//非必须参数,终端设备号
		dataMap.put("time_expire", "");//非必须参数
		dataMap.put("goods_tag", "");//非必须参数
		dataMap.put("limit_credit_pay", "");//非必须参数
		
		if (PayChannelCode.微信支付.equals(channelCode)) {
			dataMap.put("service", "pay.weixin.jspay");
//			dataMap.put("sub_appid", appId);//威富通参数
			dataMap.put("mch_id", config.getWxMchId());
//			dataMap.put("sub_openid", openid);//TODO 测试时不使用
			dataMap.put("is_raw", "1");
			dataMap.put("is_minipg", "0");//非必须参数,值为1，表示小程序支付；不传或值不为1，表示公众账号内支付
			
			String sign = PaymentKit.createSign(dataMap, config.getWxResKey());
			dataMap.put("sign", sign);
			String mapToXml = PaymentKit.mapToXml(dataMap);
			
			String result = HttpUtil.httpRequest(config.getSwiftpassGateway(), "POST", mapToXml);// 威富通接口
			String xml2json = XmlJsonUtils.xml2json(result);
			JSONObject jsonObject = JSON.parseObject(xml2json);
			logger.info("威富通对接微信主扫返回数据:" + jsonObject);
			JSONObject payInfo = jsonObject.getJSONObject("pay_info");

			payInfo.put("packageInfo", payInfo.getString("package"));
			dataMap.clear();
			dataMap.put("isok", "0");// 0未支付,1已支付
			dataMap.put("mhtOrderAmtStr", qrcodePayModel.getTollFare());
			dataMap.put("payInfo", payInfo.toJSONString());
			dataMap.put("channel", PayChannelType.payChannelCode2Type(channelCode));
			
			return new QrcodePayRes(view, dataMap);
		}else if (PayChannelCode.支付宝支付.equals(channelCode)) {
			dataMap.put("service", "pay.alipay.jspay");
			dataMap.put("mch_id", config.getAliMchId());
			
//			dataMap.put("buyer_logon_id", "buyer_logon_id");//TODO 买家支付宝账号，和buger_id不能同时为空
			dataMap.put("buyer_id", openId);//TODO 买家支付宝用户ID，和buyer_logon_id不能同时为空
			
			dataMap.put("qr_code_timeout_express", "10m");//非必须参数,该笔订单允许的最晚付款时间，逾期将关闭交易，从下单开始计时。取值范围：1m~15d
			dataMap.put("op_user_id", "");//非必须参数,操作员账号，默认为商户号
			dataMap.put("product_id", qrcodePayModel.getTranNO());//非必须参数
			
			String sign = PaymentKit.createSign(dataMap, config.getAliResKey());
			dataMap.put("sign", sign);
			String aliPayParams = PaymentKit.mapToXml(dataMap);
			String result = HttpUtil.httpRequest(config.getSwiftpassGateway(), "POST", aliPayParams);
			
			String xml2json = XmlJsonUtils.xml2json(result);
			JSONObject jsonObject = JSON.parseObject(xml2json);
			logger.info("威富通对接支付宝主扫返回数据:" + jsonObject);
			
			JSONObject payInfo = jsonObject.getJSONObject("pay_info");
			String tradeNO = payInfo.getString("tradeNO");
			
			dataMap.clear();
			dataMap.put("isok", "0");// 0未支付,1已支付
			dataMap.put("mhtOrderAmtStr", qrcodePayModel.getTollFare());
			dataMap.put("tradeNO", tradeNO);
			dataMap.put("channel", PayChannelType.payChannelCode2Type(channelCode));
			return new QrcodePayRes(view, dataMap);
		}else {
			return null;
		}
	}

	
	/**
	 * 威富通被扫支付
	 */
	@Override
	public JSONObject swipeCardPay(TradePayModel tradePayModel) {
		String mhtOrderName = tradePayModel.getOrderName();
		String mhtOrderDetail = tradePayModel.getOrderDetail();
		String mhtOrderAmt = String.valueOf(tradePayModel.getOrderAmt());
		String mhtOrderNo = tradePayModel.getTradeNo();
		String channelAuthCode = tradePayModel.getAuthCode();
		
		Map<String, String> dataMap = new HashMap<String, String>(32);
		dataMap.put("service", "unified.trade.micropay");
		dataMap.put("mch_id", config.getBeisaoMchId());
		dataMap.put("out_trade_no", mhtOrderNo);
		dataMap.put("body", mhtOrderDetail);
		dataMap.put("total_fee", mhtOrderAmt);
		dataMap.put("mch_create_ip", config.getOrderIp());
		dataMap.put("auth_code", channelAuthCode);
		dataMap.put("nonce_str", "ITC"+System.currentTimeMillis());
		
		dataMap.put("version", config.getVersion());//非必须参数
		dataMap.put("charset", config.getCharset());//非必须参数
		dataMap.put("sign_type", "MD5");//非必须参数
		dataMap.put("device_info", "");//终端设备号
		dataMap.put("goods_detail", mhtOrderName);//单品优惠活动该字段必传
		dataMap.put("attach", "");//非必须参数
		dataMap.put("op_user_id", "");//非必须参数,操作员帐号,默认为商户号
		dataMap.put("op_shop_id", "");//非必须参数,门店编号
		dataMap.put("op_device_id", "");//非必须参数,设备编号
		dataMap.put("time_start", "");//非必须参数
		dataMap.put("time_expire", "");//非必须参数
		dataMap.put("goods_tag", "");//非必须参数
		
		String sign = PaymentKit.createSign(dataMap, config.getBeisaoResKey());//测试KEY
		dataMap.put("sign", sign);
		String xml = PaymentKit.mapToXml(dataMap);
		String result = HttpUtil.httpRequest(config.getSwiftpassGateway(), "POST", xml);// 威富通接口
		
		String xml2json = XmlJsonUtils.xml2json(result);
		JSONObject jsonObject = JSON.parseObject(xml2json);
		logger.info("威富通对接被扫返回数据:" + jsonObject.toJSONString());
		return jsonObject;
	}

	/**
	 * 威富通查询订单
	 */
	@Override
	public JSONObject queryOrder(String mhtOrderNo, String payChannelType) {
		String appKey = "";
		Map<String, String> dataMap = new HashMap<String, String>();
		//支付宝
		if (PayChannelCode.支付宝支付.equals(payChannelType)) {
			appKey = config.getAliResKey();
			dataMap.put("mch_id", config.getAliMchId());
		}
		//微信
		if (PayChannelCode.微信支付.equals(payChannelType)) {
			appKey = config.getWxResKey();
			dataMap.put("mch_id", config.getWxMchId());
		}
		//被扫
		if ("bs".equals(payChannelType)) {
			appKey = config.getBeisaoResKey();
			dataMap.put("mch_id", config.getBeisaoMchId());
		}
		
		//做MD5签名
		dataMap.put("service","unified.trade.query");
		dataMap.put("nonce_str","ITC"+System.currentTimeMillis());
		dataMap.put("out_trade_no", mhtOrderNo);
		
		String mhtSignature = PaymentKit.createSign(dataMap, appKey);
		dataMap.put("sign", mhtSignature);
		String mapToXml = PaymentKit.mapToXml(dataMap);
		String result = HttpUtil.httpRequest(config.getSwiftpassGateway(), "POST", mapToXml);
		String xml2json = XmlJsonUtils.xml2json(result);
		JSONObject jsonObject = JSON.parseObject(xml2json);
		logger.info("威富通订单查询结果==="+jsonObject.toJSONString());
		return jsonObject;
	}

	/**
	 * 威富通取消订单
	 */
	@Override
	public boolean cancelOrder(TradePayModel tradePayModel) {
		String key = "";
		Map<String, String> map = new HashMap<>();
		map.put("service", "unified.micropay.reverse");
		map.put("out_trade_no", tradePayModel.getTradeNo());
		map.put("nonce_str", "ITC" + System.currentTimeMillis());
		if (PayChannelCode.微信支付.equals(tradePayModel.getPayChannelCode())) {
			map.put("mch_id", config.getWxMchId());
			key = config.getWxResKey();
		}
		if (PayChannelCode.支付宝支付.equals(tradePayModel.getPayChannelCode())) {
			map.put("mch_id", config.getAliMchId());
			key = config.getAliResKey();
		}
		map.put("version", config.getVersion());
		map.put("charset", config.getCharset());
		map.put("sign_type", "MD5");
		String sign = PaymentKit.createSign(map, key);
		map.put("sign", sign);
		String xml = PaymentKit.mapToXml(map);
		String result = HttpUtil.httpRequest(config.getSwiftpassGateway(), "POST", xml);
		String xml2json = XmlJsonUtils.xml2json(result);
		JSONObject jsonObject = JSON.parseObject(xml2json);
		logger.info("威富通撤销订单返回数据====" + jsonObject.toJSONString());
		if ("0".equals(jsonObject.getString("status"))) {
			if ("0".equals(jsonObject.getString("result_code"))) {
				return true;
			}
		}
		return false;
	}

}
